#include "log.hpp"
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <arpa/inet.h>
Log log_;


enum{
    socket_create_error = 1,
    bind_error
};


class UdpServer
{
public:
    UdpServer(uint16_t port = 8080, std::string ip = "0")
        :sockfd_(0)
        ,ip_(ip)
        ,port_(port)
    {}

    void Init()
    {
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ <= 0)
        {
            log_(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(socket_create_error);
        }
        log_(Info, "socket create success, sockfd: %d", sockfd_);
        struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(sockfd_, (const struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            log_(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(bind_error);
        }
        log_(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void start()
    {
        char buffer[1024] = {0};
        struct sockaddr_in opposite;
        socklen_t len = sizeof(struct sockaddr_in);
        while(1)
        {
            size_t n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&opposite, &len);
            if(n < 0)
            {
                log_(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
            }
            buffer[n] = 0;
            std::cout << "收到了数据"<<std::endl;
            std::string respond = "Rerver@" + std::string(buffer);
            sendto(sockfd_, respond.c_str(), respond.size(), 0, (const struct sockaddr*)&opposite, len);
        }
        
    }

    ~UdpServer(){};


private:
    int sockfd_;     //套接字文件描述符
    std::string ip_ ; // ip 地址
    uint16_t port_;     //端口号
};






